﻿/****************************************************************************************************************************
*	global variable
****************************************************************************************************************************/
var map;
var markers = new fMarkers();
var polylines = new fPolylines();
var polygons = new fPolygons();
var markerSelected = null;
// **************************************************************************************************************************

/****************************************************************************************************************************
*	functions call once when page loaded
****************************************************************************************************************************/
function DrawGoogleMap() {
    Service.GetGoogleMapObject(GetGoogleMapObjectHandler);
}

function GetGoogleMapObjectHandler(result) {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: result.ZoomLevel,
        center: new google.maps.LatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude),
        mapTypeId: result.StringMapType,
        panControl: result.PanControl,
        zoomControl: result.ZoomControl,
        mapTypeControl: result.MapTypeControl,
        scaleControl: result.ScaleControl,
        streetViewControl: result.StreetViewControl,
        overviewMapControl: result.OverviewMapControl
    };

    map = new google.maps.Map(document.getElementById("GoogleMap_Div"), myOptions);

    //////////////////////////////////////
    if (result.Panorama.Width != "0px" && result.Panorama.Height != "0px") {
        var panoramaOptions = {
            position: latlng,
            pov: 
            {
                heading: result.Panorama.heading,
                pitch: result.Panorama.pitch,
                zoom: result.Panorama.zoom
            }
        };
        var panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"), panoramaOptions);
        map.setStreetView(panorama);
    }
    /////////////////////////////////

    for (i = 0; i < result.CountControlsCurrent; i++) {
        var ControlDiv = document.createElement('DIV');
        var customControl = new CustomControl(result.Controls[i], i, ControlDiv, map);
        ControlDiv.index = i + 1;
        ControlDiv.value = i;
        map.controls[result.Controls[i].position].push(ControlDiv);
        //        google.maps.event.addDomListener(ControlDiv, 'click',
        //        function(){
        //           RaiseEvent('ControlClicked', this.value);
        //        });
    }

    var styleArray = new Array();
    for (i = 0; i < result.CountStyleCurrent; i++) {
        var style = CreateStyle(result.Styles[i]);
        styleArray.push(style);
    }
    map.setOptions({ styles: styleArray });

    map.setZoom(result.ZoomLevel);
    google.maps.event.addListener(map, 'click', function (event) {
        MapClickFunction(event.latLng);
    });

    google.maps.event.addListener(map, 'dblclick', function (event) {
        MapDBClickFunction(event.latLng);
    });

    //    google.maps.event.addListener(map, 'mouseup', function (event) {
    //        MouseUpFunction(event.latLng);
    //    });

    //    google.maps.event.addListener(map, 'mousedown', function (event) {
    //        MouseDownFunction(event.latLng);
    //    });

    //    google.maps.event.addListener(map, 'mouseover', function (event) {
    //        MouseOverFunction(event.latLng);
    //    });

    //    google.maps.event.addListener(map, 'mouseout', function (event) {
    //        MouseOutFunction(event.latLng);
    //    });

    //    google.maps.event.addListener(map, 'zoom_changed', function () {
    //        Zoom_Changed();
    //    });

    //    google.maps.event.addListener(map, 'center_changed', function () {
    //        Center_Changed();
    //    });

    //    google.maps.event.addListener(map, 'bound_changed', function () {
    //        Bound_Changed();
    //    });

    //**************Marker************************
    for (i = 0; i < result.Markers.length; i++) {
        var markerIcon = null;
        var shadowMarkerIcon = null;
        //Marker icon
        if (result.Markers[i].IconImage != '') {
            markerIcon = new google.maps.MarkerImage(result.Markers[i].IconImage,
                                                  new google.maps.Size(result.Markers[i].IconImageWidth, result.Markers[i].IconImageHeight),
                                                  new google.maps.Point(0, 0),
            // The anchor for this image is the base of the flagpole at 0,32.
                                                  new google.maps.Point(result.Markers[i].IconAnchor_posX, result.Markers[i].IconAnchor_posY));
        }
        if (result.Markers[i].IconShadowImage != '') {
            shadowMarkerIcon = new google.maps.MarkerImage(result.Markers[i].IconShadowImage,
            // The shadow image is larger in the horizontal dimension
            // while the position and offset are the same as for the main image.
                                                  new google.maps.Size(result.Markers[i].IconShadowWidth, result.Markers[i].IconShadowHeight),
                                                  new google.maps.Point(0, 0),
                                                  new google.maps.Point(result.Markers[i].IconAnchor_posX, result.Markers[i].IconAnchor_posY));
        }
        var marker = CreateMarker(result.Markers[i].ID, result.Markers[i].Position.Latitude, result.Markers[i].Position.Longitude, markerIcon, shadowMarkerIcon, result.Markers[i].InfoWindow.Text, result.Markers[i].Draggable, result.Markers[i].ToolTip);
        markers.pushValue(marker);
        markers.getLastValue().setMap(map);
    }
    //***************end***********************


    //*******************Polyline*********************
    //Get Polylines
    polylines = new fPolylines();
    for (i = 0; i < result.Polylines.length; i++) {
        var polypoints = new Array();
        var j;
        for (j = 0; j < result.Polylines[i].ArrayPoint.length; j++) {
            polypoints.push(new google.maps.LatLng(result.Polylines[i].ArrayPoint[j].Latitude, result.Polylines[i].ArrayPoint[j].Longitude));
        }
        var polyline = CreatePolyline(polypoints, result.Polylines[i].ColorCode, result.Polylines[i].Width, result.Polylines[i].Opacity);
        polylines.pushValue(polyline, result.Polylines[i].ID);
    }
    //***********************************************
    //*******************Polygon*********************
    polygons = new fPolygons();
    for (i = 0; i < result.Polygons.length; i++) {
        var polypoints = new Array();
        var j;
        for (j = 0; j < result.Polygons[i].ArrayPoint.length; j++) {
            polypoints.push(new google.maps.LatLng(result.Polygons[i].ArrayPoint[j].Latitude, result.Polygons[i].ArrayPoint[j].Longitude));

        }
        var polygon = CreatePolygon(polypoints, result.Polygons[i].StrokeColor, result.Polygons[i].StrokeWeight, result.Polygons[i].StrokeOpacity, result.Polygons[i].FillColor, result.Polygons[i].FillOpacity);
        polygons.pushValue(polygon, result.Polygons[i].ID);
    }

}
// **************************************************************************************************************************

/****************************************************************************************************************************
*	functions call regularly
****************************************************************************************************************************/

function GetGoogleMapObjecOptimizetHandler(result) {
//    if ((map.center.lat() != result.CenterPoint.Latitude || map.center.lng() != result.CenterPoint.Longitude))
//        map.setCenter(new google.maps.LatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude));
//    if (map.zoom != result.ZoomLevel)
//        map.setZoom(result.ZoomLevel);
    //**********************Marker************************
    for (i = 0; i < result.Markers.length; i++) {
        //Marker icon
        var markerIcon = null;
        var shadowMarkerIcon = null;
        if (result.Markers[i].IconImage != '') {
            markerIcon = new google.maps.MarkerImage(result.Markers[i].IconImage,
                                                  new google.maps.Size(result.Markers[i].IconImageWidth, result.Markers[i].IconImageHeight),
                                                  new google.maps.Point(0, 0),
            // The anchor for this image is the base of the flagpole at 0,32.
                                                  new google.maps.Point(result.Markers[i].IconAnchor_posX, result.Markers[i].IconAnchor_posY));
        }
        if (result.Markers[i].IconShadowImage != '') {
            shadowMarkerIcon = new google.maps.MarkerImage(result.Markers[i].IconShadowImage,
            // The shadow image is larger in the horizontal dimension
            // while the position and offset are the same as for the main image.
                                                  new google.maps.Size(result.Markers[i].IconShadowWidth, result.Markers[i].IconShadowHeight),
                                                  new google.maps.Point(0, 0),
                                                  new google.maps.Point(result.Markers[i].IconAnchor_posX, result.Markers[i].IconAnchor_posY));
        }
        //Check Markers status
        ////---------Existing marker, but changed.
        //alert(result.Markers[i].PointStatus);
        if (result.Markers[i].PointStatus == 'C') {
            var marker = markers.getValueById(result.Markers[i].ID);
            if (marker != null) {
                markers.removeValueById(result.Markers[i].ID);
                marker.setMap(null);
            }
            var marker = CreateMarker(result.Markers[i].ID, result.Markers[i].Position.Latitude, result.Markers[i].Position.Longitude, markerIcon, shadowMarkerIcon, result.Markers[i].InfoWindow.Text, result.Markers[i].Draggable, result.Markers[i].ToolTip);
            markers.pushValue(marker);
            markers.getLastValue().setMap(map); //set overlay map
        }

        //New marker
        if (result.Markers[i].PointStatus == 'N') {
            var marker = CreateMarker(result.Markers[i].ID, result.Markers[i].Position.Latitude, result.Markers[i].Position.Longitude, markerIcon, shadowMarkerIcon, result.Markers[i].InfoWindow.Text, result.Markers[i].Draggable, result.Markers[i].ToolTip);
            markers.pushValue(marker);
            markers.getLastValue().setMap(map);
        }

        //Existing marker, but deleted.
        if (result.Markers[i].PointStatus == 'D') {
            var marker = markers.getValueById(result.Markers[i].ID);
            if (marker != null) {
                markers.removeValueById(result.Markers[i].ID);
                marker.setMap(null);
            }
        }
    }

    //**********************end**************************
    //***************Polyline*****************************
    //Get Polylines

    for (i = 0; i < result.Polylines.length; i++) {
        //Existing Polyline, but changed.
        if (result.Polylines[i].LineStatus == 'C') {
            var polyline = polylines.getValueById(result.Polylines[i].ID);

            if (polyline != null) {
                polylines.removeValueById(result.Polylines[i].ID);
            }
            var polypoints = new Array();
            var j;
            for (j = 0; j < result.Polylines[i].ArrayPoint.length; j++) {
                polypoints.push(new google.maps.LatLng(result.Polylines[i].ArrayPoint[j].Latitude, result.Polylines[i].ArrayPoint[j].Longitude));
            }

            var polyline = CreatePolyline(polypoints, result.Polylines[i].ColorCode, result.Polylines[i].Width, result.Polylines[i].Opacity);
            polylines.pushValue(polyline, result.Polylines[i].ID);
        }
        //New Polyline
        if (result.Polylines[i].LineStatus == 'N') {
            var polypoints = new Array();
            var j;
            for (j = 0; j < result.Polylines[i].ArrayPoint.length; j++) {
                polypoints.push(new google.maps.LatLng(result.Polylines[i].ArrayPoint[j].Latitude, result.Polylines[i].ArrayPoint[j].Longitude));
            }
            var polyline = CreatePolyline(polypoints, result.Polylines[i].ColorCode, result.Polylines[i].Width, result.Polylines[i].Opacity);
            polylines.pushValue(polyline, result.Polylines[i].ID);
        }
        //Existing marker, but deleted.
        if (result.Polylines[i].LineStatus == 'D') {
            var polyline = polylines.getValueById(result.Polylines[i].ID);
            if (polyline != null) {
                polylines.removeValueById(result.Polylines[i].ID);
            }
        }
    }

    //**********************Polygons*********************************
    for (i = 0; i < result.Polygons.length; i++) {
        //Existing marker, but changed.
        if (result.Polygons[i].Status == 'C') {

            var polygon = polygons.getValueById(result.Polygons[i].ID);
            if (polygon != null) {
                polygons.removeValueById(result.Polygons[i].ID);
            }
            var polypoints = new Array();
            var j;
            for (j = 0; j < result.Polygons[i].ArrayPoint.length; j++) {
                polypoints.push(new google.maps.LatLng(result.Polygons[i].ArrayPoint[j].Latitude, result.Polygons[i].ArrayPoint[j].Longitude));
            }
            var polygon = CreatePolygon(polypoints, result.Polygons[i].StrokeColor, result.Polygons[i].StrokeWeight, result.Polygons[i].StrokeOpacity, result.Polygons[i].FillColor, result.Polygons[i].FillOpacity);
            polygons.pushValue(polygon, result.Polygons[i].ID);
        }
        //New Marker
        if (result.Polygons[i].Status == 'N') {
            var polypoints = new Array();
            var j;
            for (j = 0; j < result.Polygons[i].ArrayPoint.length; j++) {
                polypoints.push(new google.maps.LatLng(result.Polygons[i].ArrayPoint[j].Latitude, result.Polygons[i].ArrayPoint[j].Longitude));
            }
            var polygon = CreatePolygon(polypoints, result.Polygons[i].StrokeColor, result.Polygons[i].StrokeWeight, result.Polygons[i].StrokeOpacity, result.Polygons[i].FillColor, result.Polygons[i].FillOpacity);
            polygons.pushValue(polygon, result.Polygons[i].ID);
        }
        //Existing marker, but deleted.
        if (result.Polygons[i].Status == 'D') {
            var polygon = polygons.getValueById(result.Polygons[i].ID);
            if (polygon != null) {
                polygons.removeValueById(result.Polygons[i].ID);
            }
        }
    }
}

function endRequestHandler(sender, args) {
    Service.GetOptimizedGoogleObject(GetGoogleMapObjecOptimizetHandler);
}

function pageLoad() {
    if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}

// **************************************************************************************************************************

/****************************************************************************************************************************
*	functions
****************************************************************************************************************************/
function MapClickFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseClick', latlng.lat() + "," + latlng.lng());
    }
}

function MapDBClickFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseDoubleClick', latlng.lat() + "," + latlng.lng());
    }
}

function MouseUpFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseUp', latlng.lat() + "," + latlng.lng());
    }
}

function MouseDownFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseDown', latlng.lat() + "," + latlng.lng());
    }
}

function MouseOverFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseOver', latlng.lat() + "," + latlng.lng());
    }
}

function MouseOutFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseOut', latlng.lat() + "," + latlng.lng());
    }
}

function Zoom_Changed() {
    RaiseEvent('ZoomChanged', "");
}
function Center_Changed() {
    RaiseEvent('CenterChanged', "");
}
function Bound_Changed() {
    RaiseEvent('BoundChanged', "");
}

function PlaceMarker(latitude, longitude) {
    var position = new google.maps.LatLng(latitude, longitude);

    marker = new google.maps.Marker({
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP,
        position: position
    });
}


function CreatePolyline(CoordinatesArray, colorcode, Opacity, Width) {
    var line = new google.maps.Polyline({
        path: CoordinatesArray,
        strokeColor: colorcode,
        strokeOpacity: Opacity,
        strokeWeight: Width
    });
    line.setMap(map);
}

function CreatePolygon(CoordinatesArray, strokecolor, strokeweight, strokeopacity, fillcolor, fillopacity) {

    var polygon = new google.maps.Polygon({
        paths: CoordinatesArray,
        strokeColor: strokecolor,
        strokeOpacity: strokeopacity,
        strokeWeight: strokeweight,
        fillColor: fillcolor,
        fillOpacity: fillopacity
    });
    polygon.setMap(map);

    return polygon;
}

function CreateMarker(value, latitude, longitude, icon, iconShadow, InfoHTML, bDraggable, sTitle) {
    var position = new google.maps.LatLng(latitude, longitude);

    var infowindow = new google.maps.InfoWindow({
        content: InfoHTML
    });

    var marker = new google.maps.Marker({
        map: map,
        draggable: bDraggable,
        animation: google.maps.Animation.DROP,
        position: position,
        title: sTitle,
        shadow: iconShadow,
        icon: icon,
        infowindow: infowindow,
        value: value
    });

    google.maps.event.addListener(marker, 'click', function () {
        markerSelected = marker;
        RaiseEvent('MarkerClicked', this.value);
        Service.GetGoogleMapObject(OpenInforWindow);
    });

    google.maps.event.addListener(marker, 'rightclick', function () {
        RaiseEvent('MarkerRightClicked', this.value);
    });

    google.maps.event.addListener(marker, 'dblclick', function () {
        RaiseEvent('MarkerDblClicked', this.value);
    });

    google.maps.event.addListener(marker, 'dragend', function () {
        RaiseEvent('MarkerDrag', this.value);
    });

    return marker;
}

function CustomControl(control, index, controlDiv, map) {
    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';

    // Set CSS for the control border
    var controlUI = document.createElement('DIV');
    controlUI.style.backgroundColor = control.BackgroundColor;
    controlUI.style.borderStyle = control.BorderStyle;
    controlUI.style.borderWidth = control.BorderWidth;
    controlUI.style.cursor = control.Cursor;
    controlUI.style.textAlign = control.TextAlign;
    controlUI.title = control.Title;
    controlDiv.appendChild(controlUI);

    // Set CSS for the control interior
    var controlText = document.createElement('DIV');
    controlText.style.fontFamily = control.FontFamily;
    controlText.style.fontSize = control.FontSize;
    controlText.style.paddingLeft = control.PaddingLeft;
    controlText.style.paddingRight = control.PaddingRight;
    controlText.innerHTML = control.InnerHTML;
    controlUI.appendChild(controlText);

    // Setup the click event listeners: simply set the map to Chicago
    google.maps.event.addDomListener(controlUI, 'click', function () {
        RaiseEvent('ControlClicked', index);
    });
}

function CreateStyle(style) {
    return {
        featureType: style.Feature,
        elementType: style.Element,
        stylers: [
                        { gamma: style.gamma },
                        { hue: style.hue },
                        { invert_lightness: style.invert_lightness },
                        { saturation: style.saturation },
                        { lightness: style.lightness },
                        { visibility: style.visibility }
                    ]
    }
}

function OpenInforWindow(result) {

    for (i = 0; i < markers.getLength(); i++)
        markers.markers[i].infowindow.close();

    for (i = 0; i < result.Markers.length; i++) {
        if (result.Markers[i].InfoWindow.StatusOpened) {
            if (markerSelected.value == result.Markers[i].ID) {
                markerSelected.infowindow.open(map, markerSelected);
                return;
            }
        }
    }
}

// **************************************************************************************************************************

function fMarkers() {
    this.markers = new Array();
    this.getLength = function () { return this.markers.length; };
    this.pushValue = function (v) { this.markers.push(v); }
    this.getValue = function (i) { return this.markers[i]; }
    this.getLastValue = function () { return this.markers[this.markers.length - 1]; }
    this.getValueById = function (ID) {
        var i;
        for (i = 0; i < this.markers.length; i++) {
            if (this.markers[i].value == ID) {
                // alert('marker found : '+this.markers[i].value);
                return this.markers[i];
            }
        }
        return null;
    }
    this.removeValueById = function (ID) {
        var i;
        for (i = 0; i < this.markers.length; i++) {
            if (this.markers[i].value == ID) {
                // alert('marker found : '+this.markers[i].value);
                this.markers.splice(i, 1);
                //alert('changed marker removed');
            }
        }
        return null;
    }
}


function fPolylines() {
    this.polylines = new Array();
    this.polylinesID = new Array();
    this.getLength = function () { return this.polylines.length; };
    this.pushValue = function (v, ID) { this.polylines.push(v); this.polylinesID.push(ID); }
    this.getValue = function (i) { return this.polylines[i]; }
    this.getLastValue = function () { return this.polylines[this.polylines.length - 1]; }
    this.getValueById = function (ID) {
        var i;
        for (i = 0; i < this.polylinesID.length; i++) {
            if (this.polylinesID[i] == ID) {
                // alert('polyline found : '+this.polylines[i].value);
                return this.polylines[i];
            }
        }
        return null;
    }
    this.removeValueById = function (ID) {
        var i;
        for (i = 0; i < this.polylinesID.length; i++) {
            if (this.polylinesID[i] == ID) {
                this.polylines.splice(i, 1);
                this.polylinesID.splice(i, 1);
            }
        }
        return null;
    }
}

function fPolygons() {
    this.polygons = new Array();
    this.polygonsID = new Array();
    this.getLength = function () { return this.polygons.length; };
    this.pushValue = function (v, ID) { this.polygons.push(v); this.polygonsID.push(ID); }
    this.getValue = function (i) { return this.polygons[i]; }
    this.getLastValue = function () { return this.polygons[this.polygons.length - 1]; }
    this.getValueById = function (ID) {
        var i;
        for (i = 0; i < this.polygonsID.length; i++) {
            if (this.polygonsID[i] == ID) {
                return this.polygons[i];
            }
        }
        return null;
    }
    this.removeValueById = function (ID) {
        var i;
        for (i = 0; i < this.polygonsID.length; i++) {
            if (this.polygonsID[i] == ID) {
                this.polygons.splice(i, 1);
                this.polygonsID.splice(i, 1);
            }
        }
        return null;
    }
}
